/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年9月29日 下午5:34:25
 */
package com.absir.appserv.system.asset;

import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.bean.value.JePayStatus;
import com.absir.appserv.system.service.BeanService;
import com.absir.appserv.system.service.UcService;
import com.absir.appserv.system.service.utils.PayUtils;
import com.absir.appserv.uc.model.CpRequestHelper;
import com.absir.appserv.uc.model.PayCallbackResponse;
import com.absir.appserv.uc.model.PayCallbackResponse.PayCallbackResponseData;
import com.absir.core.dyna.DynaBinder;
import com.absir.core.kernel.KernelDyna;
import com.absir.core.kernel.KernelObject;
import com.absir.server.value.Body;
import com.absir.server.value.Server;

/**
 * @author absir
 *
 */
@Server
public class Asset_uc extends AssetServer {

	/**
	 * @param rsp
	 * @return
	 */
	@Body
	public String notify(@Body PayCallbackResponse rsp) {
		if (rsp != null && rsp.getSign() != null && rsp.getData() != null) {
			// 输出获取到的参数

			/*
			 * 假定cpId=109，apiKey=202cb962234w4ers2aaa
			 * 
			 * sign的签名规则:data的所有子参数按key升序，key=value串接即 MD5(cpId +
			 * amount=...+callbackInfo=...+failedDesc=...+gameId=...+orderId=...
			 * +
			 * orderStatus=...+payWay=...+serverId=...+ucid=...+apiKey)（去掉+；替换...
			 * 为实际值） 签名原文：
			 * 109amount=100callbackInfo=aaafailedDesc=gameId=123orderId
			 * =abcf1330orderStatus
			 * =SpayWay=1serverId=654ucid=123456202cb962234w4ers2aaa
			 */
			String sign = CpRequestHelper.createMD5Sign(rsp.getData(), "", UcService.UC_CONFIGURE.getMerchantKey());

			// System.out.println("[签名原文]"+signSource);
			// System.out.println("[签名结果]"+sign);
			if (KernelObject.equals(sign, rsp.getSign())) {
				/*
				 * 游戏服务器需要处理给玩家充值代码,由游戏合作商开发完成。
				 */
				PayCallbackResponseData data = DynaBinder.to(rsp.getData(), PayCallbackResponseData.class);
				JPayTrade payTrade = BeanService.ME.get(JPayTrade.class, data.getCpOrderId());
				if (payTrade != null) {
					payTrade.setPlatform(UcService.PLAT_FORM_NAME);
					String pay_status = data.getOrderStatus();
					payTrade.setStatus(pay_status.equals("S")
							&& KernelDyna.to(data.getAmount(), float.class) >= payTrade.getAmount() ? JePayStatus.PAYED
							: JePayStatus.ERROR);
					payTrade.setStatusData(pay_status);
					payTrade.setChannel(String.valueOf(data.getPayWay()));
					if (payTrade.getStatus() == JePayStatus.PAYED) {
						PayUtils.proccessDone(payTrade);

					} else {
						BeanService.ME.merge(payTrade);
					}
				}

				return "SUCCESS";// 返回给sdk server的响应内容
			}
		}

		return "FAILURE";
	}

}
